/*=============================================================================

    textundo.cpp  -  Copyright (C) 1998-2005 by Don Cross

=============================================================================*/

#include <stdio.h>

#include "chess.h"
#include "uistdio.h"

MoveUndoPath Global_MoveUndoPath;

MoveUndoPath::~MoveUndoPath()
{
    if ( moveList ) 
    {
        delete[] moveList;
        moveList = 0;
        current = length = size = 0;
    }
}


void MoveUndoPath::resetFromBoard ( const ChessBoard &board )
{
    if ( !moveList )
    {
        size = 1024;    // arbitrary but larger than necessary
        moveList = new Move [size];
        if ( !moveList )  
        {
            ChessFatal ( "Out of memory allocating MoveUndoPath" );
            return;
        }
    }

    current = length = board.GetCurrentPlyNumber();
    for ( int i=0; i<length; i++ )
        moveList[i] = board.GetPastMove(i);
}


bool MoveUndoPath::undo ( ChessBoard &board )
{
    // Allow undo only if board has not been edited
    if ( board.HasBeenEdited() )
    {
        printf ( "!!! Cannot undo move because board has been edited!\n" );
        return false;
    }

    if ( current < 2 )
    {
        printf ( "!!! Cannot undo this early in the game!\n" );
        return false;
    }

    board.Init();
    current -= 2;
    UnmoveInfo unmove;
    for ( int i=0; i<current; i++ )
        board.MakeMove ( moveList[i], unmove );

    return true;
}


bool MoveUndoPath::redo ( ChessBoard &board )
{
    // Allow undo only if board has not been edited
    if ( board.HasBeenEdited() )
    {
        printf ( "!!! Cannot redo move because board has been edited!\n" );
        return false;
    }

    if ( current + 2 > length )
    {
        printf ( "!!! At end of redo list!\n" );
        return false;
    }

    UnmoveInfo unmove;
    board.MakeMove ( moveList[current], unmove );
    board.MakeMove ( moveList[current+1], unmove );
    current += 2;

    return true;
}
